package com.godyao.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.godyao.pojo.SecKillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import static com.godyao.service.impl.SecKillServiceImpl.SEC_KILL_GOODS_KEY_PREFIX;


/**
 * @author godyao
 * @date 2022/3/18
 */
@Slf4j
@Component
public class RabbitMqConsumer {
    @Autowired
    private SecKillService secKillService;

    @Autowired
    private RedisTemplate redisTemplate;


    //@RabbitListener(queues = "myQueue")
    //public void consume(String message) {
    //    System.out.println("消费到消息：" + message);
    //}

    @RabbitListener(queues = "secKillQueue")
    public void consume(String message) {
        log.info("收到消息：msg={}", message);
        String userGoodKey = null;
        try {
            final SecKillMessage secKillMessage = new ObjectMapper().readValue(message, SecKillMessage.class);
            userGoodKey =  "userId=" + secKillMessage.getUserId() + "goodsId=" + secKillMessage.getGoodsId();
            secKillService.makeOrder(secKillMessage);
            log.info("下单成功");
        } catch (Exception e) {
            // 库存是否加回去 ？？
            if (!StringUtils.isEmpty(userGoodKey))  redisTemplate.opsForValue().increment(SEC_KILL_GOODS_KEY_PREFIX + userGoodKey);
            log.error("下单失败, msg={}", e.getLocalizedMessage());
        }
    }
}
